package service

import (
	"bytes"
	"encoding/json"
	"goHttp/config"
	"io"
	"log"
	"net/http"
	"os"
	"time"
)

func Do(url string, start, end time.Time, startName, endName, token string) (int, []byte) {
	request := map[string]string{
		startName: start.Format(time.DateTime),
		endName:   end.Format(time.DateTime),
	}

	reqBytes, err := json.Marshal(request)
	if err != nil {
		panic("转换为json bytes失败" + err.Error())
	}

	//创建请求对象
	req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(reqBytes))
	if err != nil {
		log.Println("创建请求对象失败：", err.Error(), url)

		os.Exit(1)
	}

	if len(token) > 0 {
		req.Header.Set("Authorization", token)
	}

	if len(config.C.Header.ContentType) > 0 {
		req.Header.Set("Content-Type", config.C.Header.ContentType)
	}
	if len(config.C.Header.UserAgent) > 0 {
		req.Header.Set("User-Agent", config.C.Header.UserAgent)
	}

	if len(config.C.Header.Authorization) > 0 {
		req.Header.Set("Authorization", config.C.Header.Authorization)
	}

	if len(config.C.Header.Referer) > 0 {
		req.Header.Set("Referer", config.C.Header.Referer)

	}

	//创建一个http客户端
	client := &http.Client{}

	//发起请求
	resp, err := client.Do(req)
	if err != nil {
		log.Println("发送请求失败：", err.Error(), url)
		os.Exit(1)
	}

	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Println("获取请求内容失败：", err.Error(), url)

		os.Exit(1)
	}
	return resp.StatusCode, body
}
